package com.tubruk.todo.activity;

import java.util.ArrayList;


import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;

import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import com.tubruk.todo.activity.R;
import com.tubruk.todo.database.TodoAdapter;
import com.tubruk.todo.Global;
import com.tubruk.todo.TaskAdapter;
import com.tubruk.todo.TaskContent;
import com.tubruk.todo.Todos;
import com.tubruk.util.dialog.ListMenu;
import com.tubruk.todo.PopMenu;

public class TodoActivity extends Activity {
	/** Called when the activity is first created. */

	private Runnable viewTasks;
	private Runnable viewChildTasks;
	
	public static final int LISTMENU_DIALOG_ID = 1;
	public static final int LISTMENU_SUBTASK_DIALOG_ID = 2;
	
	public static final int MENU_ITEM_DELETE = Menu.FIRST;
    public static final int MENU_ITEM_INSERT = Menu.FIRST + 1;
    public static final int MENU_ITEM_FILTER = Menu.FIRST + 2;
    public static final int MENU_ITEM_INFO = Menu.FIRST + 3;
    
    private ProgressDialog progressDialog = null; 
    
	private TaskAdapter adapter = null;
	private ListView list = null;
	private ArrayList<TaskContent> items = null;
	private ArrayList<TaskContent> childItems = null;
	
	private ArrayList<PopMenu> taskmenus = null;
	private ArrayList<PopMenu> tasksubmenus = null;
	
	private int selectedItemId;
	
	public void setSelectedItemId(int id){
		this.selectedItemId = id;
	}
	
	public int getSelectedItemId(){
		return this.selectedItemId;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//remove title
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		// If no data was given in the intent (because we were started
		// as a MAIN activity), then use our default content provider.
		Intent intent = getIntent();
		if (intent.getData() == null) {
			intent.setData(Todos.Todo.CONTENT_URI);
		}
		
		//set main layout
		setContentView(R.layout.main);
		
		//instantiate list view
		list = (ListView) this.findViewById(R.id.ListView);
		
		Button addBtn = (Button) this.findViewById(R.id.addtask);
		addBtn.setOnClickListener(new AddHandler());
		
		taskmenus = new ArrayList<PopMenu>();
		taskmenus.add(new PopMenu(android.R.drawable.ic_input_get, "Modify Task"));
		taskmenus.add(new PopMenu(android.R.drawable.ic_input_add, "Add New Sub-Task"));
		taskmenus.add(new PopMenu(android.R.drawable.ic_delete, "Remove Task"));
		taskmenus.add(new PopMenu(PopMenu.NO_IMAGE, "  Close"));
		
		tasksubmenus = new ArrayList<PopMenu>();
		tasksubmenus.add(new PopMenu(android.R.drawable.ic_input_get, "Modify Task"));
		tasksubmenus.add(new PopMenu(android.R.drawable.ic_delete, "Remove Task"));
		tasksubmenus.add(new PopMenu(PopMenu.NO_IMAGE, "  Close"));
	
		items = new ArrayList<TaskContent>();
		adapter = new TaskAdapter(this, R.id.ListView, new ArrayList<TaskContent>());
		//adapter.setActivity(this);
		
		//bind list
		list.setAdapter(adapter);
		
		viewTasks = new Runnable(){
            public void run() {
            	getParentTasks();
            }
        };
        
        viewChildTasks = null;
        refreshData();
	}
	
	private void refreshData(){
		adapter.clear();
		adapter.notifyDataSetChanged();
	    Thread thread =  new Thread(null, viewTasks, "MagentoBackground");
        thread.start();
        progressDialog = ProgressDialog.show(this,    
              "Please wait...", "Retrieving data ...", true);
	}
	
	public void closeTask(int parentId){
		this.setSelectedItemId(parentId);
		
		ArrayList<TaskContent> items = adapter.getItems();
		
		int size = items.size();
		ArrayList<TaskContent> toBeRemoved = new ArrayList<TaskContent>();
		for(int i=0;i<size;i++){
			TaskContent o = items.get(i);
			if (o.getParentId() == parentId){
				toBeRemoved.add(o);		
			}
		}
		items.removeAll(toBeRemoved);
		
		adapter.notifyDataSetChanged();
		//adapter.notifyAll();
	}
	
	public void dropTask(int parentId){
		Log.d("TodoActivity", "DROP TASK WAS CLICKED");
		this.setSelectedItemId(parentId);
		Log.d("TodoActivity", "PARENT ID SELECTED: " + parentId);
		if (viewChildTasks == null){
			viewChildTasks = new Runnable() {
				public void run() {
					getChildTasks();
				}
			};
		}
		
	    Thread thread =  new Thread(null, viewChildTasks, "MagentoBackground");
        thread.start();
        progressDialog = ProgressDialog.show(this,    
              "Please wait...", "Retrieving data ...", true);
	}
	
	private void getChildTasks(){
		Log.d("TodoActivity", "GET CHILD TASKS");
		childItems = TodoAdapter.getChildTasks(items, this.getSelectedItemId());
		runOnUiThread(returnChildRes);
	}
	
	private Runnable returnChildRes = new Runnable() {
		public void run() {
			ArrayList<TaskContent> items = adapter.getItems();
			int size = items.size();
			if (childItems != null) {
				for (int i = 0; i < size; i++) {
					TaskContent o = items.get(i);
					if (o.getId() == TodoActivity.this.getSelectedItemId()) {
						int childSize = childItems.size();
						for (int j = 0; j < childSize; j++) {
							items.add(++i, childItems.get(j));
						}
						break;
					}
				}
			}
			progressDialog.dismiss();
			adapter.notifyDataSetChanged();
		}
	};
	
	private void getParentTasks(){
		items = TodoAdapter.getParentTaskContent(getContentResolver(), Todos.Todo.DEFAULT_SORT_ORDER);
		runOnUiThread(returnRes);
	}
	
	private Runnable returnRes = new Runnable() {
        public void run() {
        	adapter.clear();
            if(items != null && items.size() > 0){
                //adapter.notifyDataSetChanged();
                int size = items.size();
                for(int i=0;i<size;i++){
                	adapter.add(items.get(i));
                }
            }
            progressDialog.dismiss();
            adapter.notifyDataSetChanged();
        }
	};
	
	private class AddHandler implements View.OnClickListener {
		public void onClick(View v) {
			//handle add item on to AddItem activity
			Intent i = new Intent();
			i.setClass(TodoActivity.this, AddItemActivity.class);
			
			startActivityForResult(i, Global.ACTIVITY_ADD_ITEM);
			
		}
	}
	
	@Override 
	public void onActivityResult(int requestCode, int resultCode, Intent data) {     
	  super.onActivityResult(requestCode, resultCode, data); 
	  switch(requestCode) { 
	    case (Global.ACTIVITY_ADD_ITEM) : { 
	      if (resultCode == Activity.RESULT_OK) { 
		      refreshData();
	      } 
	      break; 
	    } 
	  } 
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        // This is our one standard application action -- inserting a
        // new note into the list.
        menu.add(0, MENU_ITEM_INSERT, 0, R.string.menu_insert)
        .setShortcut('3', 'a')
        .setIcon(android.R.drawable.ic_menu_add);
        
        menu.add(1, MENU_ITEM_FILTER, 0, R.string.menu_filter)
        .setShortcut('3', 'a')
        .setIcon(android.R.drawable.ic_menu_edit);
       
        menu.add(2, MENU_ITEM_INFO, 0, R.string.menu_info)
        .setShortcut('3', 'a')
        .setIcon(android.R.drawable.ic_menu_info_details);

        return true;
    }
	
	@Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        final boolean haveItems = list.getCount() > 0;

        // If there are any notes in the list (which implies that one of
        // them is selected), then we need to generate the actions that
        // can be performed on the current selection.  This will be a combination
        // of our own specific actions along with any extensions that can be
        // found.
        if (haveItems) {
            // This is the selected item.
            Uri uri = ContentUris.withAppendedId(getIntent().getData(), list.getSelectedItemId());

            // Build menu...  always starts with the EDIT action...
            Intent[] specifics = new Intent[1];
            specifics[0] = new Intent(Intent.ACTION_EDIT, uri);
            MenuItem[] items = new MenuItem[1];

            // ... is followed by whatever other actions are available...
            Intent intent = new Intent(null, uri);
            intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
            menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0, null, specifics, intent, 0,
                    items);

            // Give a shortcut to the edit action.
            if (items[0] != null) {
                items[0].setShortcut('1', 'e');
            }
        } else {
            menu.removeGroup(Menu.CATEGORY_ALTERNATIVE);
        }
        return true;
    }
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_ITEM_INSERT:
            // Launch activity to insert a new item
            //startActivity(new Intent(Intent.ACTION_INSERT, getIntent().getData()));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
	
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);
        
        String action = getIntent().getAction();
        if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) {
            // The caller is waiting for us to return a note selected by
            // the user.  The have clicked on one, so return it now.
            setResult(RESULT_OK, new Intent().setData(uri));
        } else {
            // Launch activity to view/edit the currently selected item
            startActivity(new Intent(Intent.ACTION_EDIT, uri));
        }
    }
    
    protected Dialog onCreateDialog(int id){
		switch(id) {
		case LISTMENU_DIALOG_ID:
			return new ListMenu(this, new ListMenuListener(), taskmenus);
		case LISTMENU_SUBTASK_DIALOG_ID:
			return new ListMenu(this, new ListMenuSubTaskListener(), tasksubmenus);
		}
		return null;
	}
    
    private class ListMenuListener implements ListMenu.ListMenuListener {
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			Log.d("TEST INDEX: ", "INDEX: " + arg2);
			if (arg2 == 0) {
				Intent intent = new Intent();
				intent.setClass(TodoActivity.this, AddItemActivity.class);
				intent.putExtra(Todos.Todo._ID, TodoActivity.this.getSelectedItemId());
				startActivityForResult(intent, Global.ACTIVITY_ADD_ITEM);
			} else if (arg2 == 1){
				Intent intent = new Intent();
				intent.setClass(TodoActivity.this, AddItemActivity.class);
				intent.putExtra(Todos.Todo.PARENT_ID, TodoActivity.this.getSelectedItemId());
				startActivityForResult(intent, Global.ACTIVITY_ADD_ITEM);
			} else if (arg2 == 2){
				TodoActivity.this.deleteItem(TodoActivity.this.getSelectedItemId());
			}
		}
    }
    
    private void deleteItem(int id){
    	ArrayList<TaskContent> items = adapter.getItems();
    	int size = items.size();
    	
    	ArrayList<TaskContent> toBeRemoved = new ArrayList<TaskContent>();
    	for (int i=0;i<size;i++){
    		TaskContent o = items.get(i);
    		if (o.getId() == id || o.getParentId() == id) {
    			toBeRemoved.add(o);
    		}
    	}
    	items.removeAll(toBeRemoved);
    	TodoAdapter.delete(getContentResolver(), id);
    	adapter.notifyDataSetChanged();
    }
    
    private class ListMenuSubTaskListener implements ListMenu.ListMenuListener {
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			Log.d("TEST INDEX: ", "INDEX: " + arg2);
			if (arg2 == 1) {
				TodoActivity.this.deleteItem(TodoActivity.this.getSelectedItemId());
			}
		}
    }
}